import {
    _decorator,
    Component,
    Label,
    Node,
    Size,
    Sprite,
    Touch,
    UITransform,
    v2,
    v3,
    Vec2,
    Vec4,
} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('MyPageMove')
export class MyPageMove extends Component {
    @property(Label)
    label: Label = null!;

    vector4: Vec4 = new Vec4(0, 0, 0, 0);

    size: Size = Size.ZERO;
    onLoad() {
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);

        this.size = this.node.getComponent(UITransform)!.contentSize;
    }

    start() {
        const sp = this.node.getComponent(Sprite)!;
        const meta = sp.getRenderMaterial(0);
    }

    update(deltaTime: number) {}

    onTouchStart(touch: Touch) {
        this.vector4.z = touch.getLocationX();
        this.vector4.w = touch.getLocationY();

        this.label.string = this.vector4.toString();
    }

    onTouchMove(touch: Touch) {
        let trans = this.node.getComponent(UITransform);
        let mouse = touch.getLocation();
        this.vector4.x = mouse.x;
        this.vector4.y = mouse.y;

        let moveDir = this.getMoveDir();

        const distance1 = Vec2.distance(
            v2(this.vector4.x, this.vector4.y),
            v2(this.vector4.z, this.vector4.w),
        );
        this.label.string = `${distance1}`;
        console.log(distance1);
        this.setProperty('distance1', 1 - distance1 / trans.width);
        this.setProperty('mouseDir', moveDir);
    }

    getMoveDir() {
        let moveDir = v2(
            this.vector4.z - this.vector4.x,
            this.vector4.w - this.vector4.y,
        ).normalize();
        if (Math.abs(moveDir.x) > Math.abs(moveDir.y)) {
            if (moveDir.x > 0) {
                return v2(1, 0);
            } else {
                return v2(-1, 0);
            }
        } else {
            if (moveDir.y > 0) {
                return v2(0, 1);
            } else {
                return v2(0, -1);
            }
        }
    }

    onTouchEnd() {}

    setProperty(property: string, data: any) {
        const sp = this.node.getComponent(Sprite)!;
        const meta = sp.getRenderMaterial(0)!;
        meta.setProperty(property, data);
    }
}
